import { Button, Form, Input, Toast, Popup, Picker, DatePicker } from 'antd-mobile';
import axios from 'axios';
import { useState, useEffect } from 'react';
import { useSelector } from 'react-redux';
import './index.css';
import { request } from '../../utils';

function Book( {loadMore}) {
  const [value, setValue] = useState([]);
  const [billtypevalue, setBilltypevalue] = useState(null);
  const [billvisible, setBillVisible] = useState(false);
  const [isRecording, setIsRecording] = useState(false);
  const [recognition, setRecognition] = useState(null);
  const [visible, setVisible] = useState(false);
  const [pickerVisible, setPickerVisible] = useState(false);
  const [data, setData] = useState(null);
  const billtype = useSelector(state => state.billtype.billtype);
  const typevalue = billtype.map(item => ({ label: item.name, value: item.id }));
  const now = new Date();

  useEffect(() => {
    if ('SpeechRecognition' in window || 'webkitSpeechRecognition' in window) {
      const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
      const recognition = new SpeechRecognition();
      recognition.continuous = true;
      recognition.lang = 'zh-CN';
      recognition.interimResults = false;
      recognition.onend = () => {
        setIsRecording(false);
      };
      recognition.onresult = async (event) => {
        const transcript = Array.from(event.results)
          .map(result => result[0].transcript)
          .join('');
        const text = `${transcript}当前时间为${now}根据以上信息提取json数据${billtype.map(item => `${item.id}:${item.name}`)}里的bill_type_id和bill_time(格式YYYY-MM-DD HH:mm:ss)，remark，amount并且只返回json数据不带空格换行等符号`;
        const { data } = await axios.post('/api/api/process-ai', { text });
        const parsedData = JSON.parse(data.result);
        const mapData = Object.entries(parsedData).map(([key, value]) => ({
          field: key,
          value
        }));
        setValue(mapData);
        console.log(mapData.bill_type_id);
        setBillVisible(true);
      };
      recognition.onerror = (event) => {
        Toast.show('识别错误: ' + event.error);
        setIsRecording(false);
      };
      setRecognition(recognition);
    } else {
      Toast.show('当前浏览器不支持语音输入');
    }
  }, []);

  const toggleVoiceInput = () => {
    if (!isRecording) {
      recognition.start();
      setIsRecording(true);
    } else {
      recognition.stop();
      setIsRecording(false);
    }
  };

  const handleSubmit = async (formValues) => {
    if(billtypevalue)formValues.bill_type_id = billtypevalue;
    if (data) formValues.bill_time = data.toISOString();
    console.log(formValues);
    await request.post('api/auth/bills', formValues);
    setBillVisible(false);
    loadMore(true);
  };

  return (
    <div style={{ alignItems: 'center', gap: 8 }}>
      <div>
        <Button
          color={isRecording ? 'danger' : 'warning'}
          onTouchStart={toggleVoiceInput}
          onMouseDown={toggleVoiceInput}
          onTouchEnd={() => {
            if (isRecording) toggleVoiceInput();
          }}
          onMouseUp={() => {
            if (isRecording) toggleVoiceInput();
          }}
        >
          {isRecording ? '停止录音' : '开始录音'}
        </Button>
      </div>
      <Popup visible={billvisible} onMaskClick={() => setBillVisible(false)}>
        <Form
          layout="vertical"
          onFinish={handleSubmit}
          footer={
            <Button block type='submit' color='primary' size='large'>
              提交
            </Button>
            }
          initialValues={value.reduce((acc, item) => ({ ...acc, [item.field]: item.value }), {})}
        >
          {value.map((item, index) => (
            <Form.Item key={index} name={item.field} label={item.field === 'bill_type_id' ? '类型' : item.field === 'bill_time' ? '时间' :item.field === 'remark' ? '备注' : '金额'}>
              {item.field === 'bill_type_id' ? (
                <div onClick={() => setVisible(true)}>
                  {billtypevalue ?billtype.find(t => t.id == billtypevalue).name :billtype.find(t => t.id === item.value)?.name}
                </div>
              ) : item.field === 'bill_time' ? (
                <div onClick={() => {setPickerVisible(true)
                }}>
                  {data?data.toLocaleString():item.value}
                </div>
                
              ) : (
                <Input placeholder="请输入内容" />
              )}
            </Form.Item>
          ))}
        </Form>
      </Popup>
      <Picker
        visible={visible}
        columns={[typevalue]}
        onClose={() => {
          setVisible(false);
        }}
        onConfirm={(value) => {
          setBilltypevalue(value[0]);
          console.log(value[0]);}}
      />
      <DatePicker
        value={new Date(value.bill_time)}
        visible={pickerVisible}
        onClose={() => setPickerVisible(false)}
        onConfirm={(val) => {
          setData(val);
        }}
      />
    </div>
  );
}

export default Book;